package com.hxci.pointmap.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hxci.pointmap.service.DevService;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/deviceServlet")
@MultipartConfig
public class DevServlet extends HttpServlet {
    DevService devService = new DevService();
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        String actionType = req.getParameter("actionType");
        System.out.println("actionType = " + actionType);

        // 检查是否需要返回JSON格式数据
        String ajaxHeader = req.getHeader("X-Requested-With");
        boolean isAjax = "XMLHttpRequest".equals(ajaxHeader) || 
                        req.getParameter("format") != null && "json".equals(req.getParameter("format"));

        // 设置响应内容类型
        if (isAjax) {
            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");
        } else {
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");
        }

        if("devAdd".equals(actionType)) {
            devService.doAddDev(req, resp);
        }
        if("doQueryDev".equals(actionType)){
            System.out.println("query");
            if (isAjax) {
                // 返回JSON格式数据
                doQueryDevJson(req, resp);
            } else {
                // 返回JSP页面
                devService.doQueryDev(req, resp);
            }
        }

        if ("updateDev".equals(actionType)) {
            devService.updateDev(req, resp);
        }

        if ("doUpdateDev".equals(actionType)) {
            if (isAjax && req.getParameter("devId") != null) {
                // 返回单个设备信息的JSON
                doGetSingleDevJson(req, resp);
            } else {
                devService.doUpdateDev(req, resp);
            }
        }
        
        if ("getDevice".equals(actionType)) {
            // 通过AJAX获取设备信息
            doGetSingleDevJson(req, resp);
        }



        if ("doDeleteDev".equals(actionType)) {
            if (isAjax) {
                // 返回JSON格式数据
                doDeleteDevJson(req, resp);
            } else {
                // 返回JSP页面
                devService.doDeleteDev(req, resp);
            }
        }
    }

    /**
     * 以JSON格式返回设备查询结果
     */
    private void doQueryDevJson(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            // 获取查询参数
            String devName = req.getParameter("devName");
            if (devName == null) {
                devName = "";
            }
            String devType = req.getParameter("devType");

            // 分页参数
            int currentPage = 1;
            int pageSize = 10; // 默认每页10条
            String currentPageStr = req.getParameter("currentPage");
            String pageSizeStr = req.getParameter("pageSize");

            if (currentPageStr != null && !currentPageStr.isEmpty()) {
                currentPage = Integer.parseInt(currentPageStr);
            }
            if (pageSizeStr != null && !pageSizeStr.isEmpty()) {
                pageSize = Integer.parseInt(pageSizeStr);
            }

            // 计算起始索引
            int startIdx = (currentPage - 1) * pageSize;

            // 构建查询SQL
            String sql = " SELECT " +
                    " t.dev_id, " +
                    " t.dev_name, " +
                    " t.dev_type, " +
                    " t.lat, " +
                    " t.lon, " +
                    " ifnull(t.is_valid,'') as is_valid, " +
                    " ifnull(t.icon_name,'') as icon_name " +
                    " FROM " +
                    " device_info t " +
                    " WHERE " +
                    "  t.dev_name LIKE '%" + devName + "%'   ";
            if (devType != null && !devType.equals("")) {
                sql = sql + "   AND t.dev_type = '" + devType + "' ";
            }

            // 查询总数
            String countSQL = "select count(1) cnt from ( " + sql + " ) tab ";
            List<Map<String, Object>> countList = devService.getDevDAO().queryDevList(countSQL, new ArrayList<>());
            int totalCount = Integer.parseInt(countList.get(0).get("cnt").toString());

            // 查询分页数据
            sql = sql + " LIMIT " + startIdx + "," + pageSize;
            List<Map<String, Object>> resultList = devService.getDevDAO().queryDevList(sql, new ArrayList<>());

            // 确保结果不为空
            if (resultList == null) {
                resultList = new ArrayList<>();
            }

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("devices", resultList);
            result.put("totalCount", totalCount);
            result.put("currentPage", currentPage);
            result.put("pageSize", pageSize);

            // 设置响应内容类型
            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");

            // 写入JSON响应
            objectMapper.writeValue(resp.getWriter(), result);
        } catch (Exception e) {
            e.printStackTrace();

            // 错误响应
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", "查询设备失败: " + e.getMessage());

            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");
            objectMapper.writeValue(resp.getWriter(), errorResult);
        }
    }

    /**
     * 以JSON格式返回单个设备信息
     */
    private void doGetSingleDevJson(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            String devId = req.getParameter("devId");
            if (devId == null || devId.isEmpty()) {
                throw new IllegalArgumentException("设备ID不能为空");
            }

            // 查询设备信息
            String sql = " SELECT " +
                    " t.dev_id, " +
                    " t.dev_name, " +
                    " t.dev_type, " +
                    " t.lat, " +
                    " t.lon, " +
                    " ifnull(t.is_valid,'') as is_valid, " +
                    " ifnull(t.icon_name,'') as icon_name " +
                    " FROM " +
                    " device_info t " +
                    " WHERE " +
                    " t.dev_id = " + devId;

            List<Map<String, Object>> resultList = devService.getDevDAO().queryDevList(sql, new ArrayList<>());

            if (resultList == null || resultList.isEmpty()) {
                throw new IllegalArgumentException("未找到设备信息");
            }

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("device", resultList.get(0));

            // 设置响应内容类型
            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");

            // 写入JSON响应
            objectMapper.writeValue(resp.getWriter(), result);
        } catch (Exception e) {
            e.printStackTrace();

            // 错误响应
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", "获取设备信息失败: " + e.getMessage());

            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");
            objectMapper.writeValue(resp.getWriter(), errorResult);
        }
    }

    /**
     * 以JSON格式返回设备删除结果
     */
    private void doDeleteDevJson(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            String devId = req.getParameter("devId");
            List<Object> paramList = new ArrayList<>();
            paramList.add(devId);

            int result = devService.getDevDAO().deleteDev(paramList);

            Map<String, Object> responseResult = new HashMap<>();
            if (result > 0) {
                responseResult.put("success", true);
                responseResult.put("message", "设备删除成功");
            } else {
                responseResult.put("success", false);
                responseResult.put("message", "设备删除失败");
            }

            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");
            objectMapper.writeValue(resp.getWriter(), responseResult);
        } catch (Exception e) {
            e.printStackTrace();

            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", "删除设备时发生错误: " + e.getMessage());

            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");
            objectMapper.writeValue(resp.getWriter(), errorResult);
        }
    }
}
